package com.weijianhuawen.wjblog.jwt.config;

import com.weijianhuawen.wjblog.jwt.filter.JwtAuthenticationFilter;
import com.weijianhuawen.wjblog.jwt.handler.RestAuthenticationFailureHandler;
import com.weijianhuawen.wjblog.jwt.handler.RestAuthenticationSuccessHandler;
import lombok.Builder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


import javax.annotation.Resource;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description: jwt身份认证配置
 * @date: 2024-10-16 23:41
 */

@Configuration
public class JwtAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    @Resource
    private RestAuthenticationSuccessHandler successHandler;
    @Resource
    private RestAuthenticationFailureHandler failureHandler;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Resource
    private UserDetailsService service;

    @Override
    public void configure(HttpSecurity builder) throws Exception {
        //自定义用于jwt的身份验证过滤器
        JwtAuthenticationFilter filter = new JwtAuthenticationFilter();
        filter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));

        //设置登录认证成功对应的处理
        filter.setAuthenticationSuccessHandler(successHandler);
        //登录失败对应处理
        filter.setAuthenticationFailureHandler(failureHandler);

        //使用Spring security 默认的身份认证工具
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        //设置userDetailService，用于获取用户信息
        daoAuthenticationProvider.setUserDetailsService(service);
        //设置加密算法
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        builder.authenticationProvider(daoAuthenticationProvider);
        //将该过滤器设置UsernamePasswordAuthenticationFilter 之前执行
        builder.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
    }
}
